//
//  TSMutipleCheckTableViewController.m
//  chart
//
//  Created by xu on 15/8/2.
//  Copyright (c) 2015年 xu. All rights reserved.
//

#import "TSMutipleCheckTableViewController.h"
#import "TSMultipleCheckCell.h"
#import "TSRecieverListModel.h"
#import "TSMsgContentItemCell.h"

@interface TSMutipleCheckTableViewController ()<UITextFieldDelegate,UIActionSheetDelegate>

@end


@implementation TSMutipleCheckTableViewController
{
    NSArray *rowsArray;
    NSMutableArray *rowsSelectedArray;
    UITextField *searchTextField;
    NSMutableArray *selectedUserModel ;
    NSArray<TSUserModel> *nowList;
}
@synthesize section;
- (void)viewDidLoad {
    [super viewDidLoad];
    selectedUserModel  = [[NSMutableArray alloc] initWithCapacity:1];
    if (self.toolBarTextFieldType == ToolBarTextField_Type_Recipient) {
        self.title = @"接收人";
        [self getAllUsers];
    }else if (self.toolBarTextFieldType == ToolBarTextField_Type_Receive) {
        self.title = @"主办人";
        [self getAllUsers];
    }
    else if (self.toolBarTextFieldType == ToolBarTextField_Type_Supervise) {
        self.title = @"监督人";
        [self getAllUsers];
    }
    else if (self.toolBarTextFieldType == ToolBarTextField_Type_Audit){
        self.title = @"审核人";
        [self getAllUsers];
    }
    else if (self.toolBarTextFieldType == ToolBarTextField_Type_AddSupervise){
        self.title = @"添加监督人";
        [self getAllUsers];
    }
    else if (self.toolBarTextFieldType == ToolBarTextField_Type_Section){
        self.title = @"部门列表";
        [self getAllSections];
    }
    
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(onCloseVC)];
    [self.navigationItem setLeftBarButtonItem:barButtonItem];
    
    barButtonItem = [[UIBarButtonItem alloc] initWithTitle:nil style:UIBarButtonItemStylePlain target:self action:@selector(onSelectCompelete)];
    barButtonItem.image =[UIImage imageNamed:@"topic_follow_add"];
    [self.navigationItem setRightBarButtonItem:barButtonItem];
}

- (void)getAllUsers
{
    TSRecieverListModel *model = [[TSRecieverListModel alloc] init];
    model.requestParams = @{@"pageIndex":@(0), @"pageSize":@(10)};
    WS(weakSelf);
    [model fetchWithPath:kRequestUrl_SendMessage_outList_ableMessage completionHandler:^(BOOL isSucceeded, NSError *error) {
        __strong typeof (weakSelf)strongSelf = weakSelf;
        if (isSucceeded) {
            strongSelf->rowsArray = model.list;
            nowList = model.list;
            [weakSelf createRowsSelectedArray:model.list.count];
            [weakSelf.tableView reloadData];
        }
    } NoProgress:NO];
}

- (void)getAllUsers:(NSString *)key
{
    TSRecieverListModel *model = [[TSRecieverListModel alloc] init];
    model.requestParams = @{@"pageIndex":@(0), @"pageSize":@(10),@"name":key};
    WS(weakSelf);
    [model fetchWithPath:kRequestUrl_SendMessage_outList_byName completionHandler:^(BOOL isSucceeded, NSError *error) {
        __strong typeof (weakSelf)strongSelf = weakSelf;
        if (isSucceeded) {
            strongSelf->rowsArray = model.list;
            nowList = model.list;
            [weakSelf createRowsSelectedArray:model.list.count];
            [weakSelf.tableView reloadData];
        }
    } NoProgress:NO];
}

- (void)getAllSections
{
    TSRecieverListModel *model = [[TSRecieverListModel alloc] init];
    model.requestParams = @{@"pageIndex":@(0), @"pageSize":@(100)};
    WS(weakSelf);
    [model fetchWithPath:kRequestUrl_Section_outList_section_all completionHandler:^(BOOL isSucceeded, NSError *error) {
        __strong typeof (weakSelf)strongSelf = weakSelf;
        if (isSucceeded) {
            
            strongSelf->rowsArray = model.list;
            [weakSelf createRowsSelectedArray:model.list.count];
            
            [weakSelf.tableView reloadData];
        }
    } NoProgress:NO];
}

- (void)createRowsSelectedArray:(NSUInteger)count
{
    rowsSelectedArray = [[NSMutableArray alloc] initWithCapacity:rowsArray.count];
    for (int i=0; i<count; i++) {
        [rowsSelectedArray addObject:[NSNumber numberWithBool:NO]];
    }
}

- (void)onCloseVC
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

/* 多选后完成通知出去 */
- (void)onSelectCompelete
{
    UIActionSheet *action_sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"完成", @"全选",@"反选", nil];
    [action_sheet showInView:self.view];
}

- (NSArray *)findAllYesNames
{
//    NSMutableArray *yes_names = [[NSMutableArray alloc] initWithCapacity:1];
//    
//    for (int i=0; i<rowsSelectedArray.count; i++) {
//        NSNumber *selected = [rowsSelectedArray objectAtIndex:i];
//        if (selected.boolValue) {
//            if (rowsArray && rowsArray.count > i) {
//                TSUserModel *model = [rowsArray objectAtIndex:i];
//                [yes_names addObject:model];
//            }
//        }
//    }
//    
    return selectedUserModel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [rowsArray count];
}
-(UIView*) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(searchTextField ==nil){
        searchTextField = [[UITextField alloc] init];
        searchTextField.placeholder = @"搜索";
        searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [self setUpFieldProperties:searchTextField];
    }
    return searchTextField;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if([self.title isEqualToString:@"部门列表"]){
        return 0;
    }
    return 30.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TSMultipleCheckCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier"];
    if (!cell) {
        cell = [[TSMultipleCheckCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseIdentifier"];
    }
    
    [self removeAllSubviews:cell];
    
    if (rowsArray.count > indexPath.row) {
        TSUserModel *model = [rowsArray objectAtIndex:indexPath.row];
        BOOL isSelected = [self isSelected:model.userId];
        UIImageView *image_view = [self createImageView:isSelected?@"cell_selected":@"cell_not_selected"];
        [cell.contentView addSubview:image_view];
        UILabel *label = [self createLabel:model.name];
        [cell.contentView addSubview:label];
        
    }
    
    return cell;
}
-(BOOL)isSelected:(NSString *)userId
{
    for(TSUserModel *user in selectedUserModel){
        if([user.userId isEqualToString:userId]){
            return YES;
        }
    }
    return NO;
}

- (void)removeAllSubviews:(UITableViewCell *)cell
{
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
}

- (UIImageView *)createImageView:(NSString *)imageName
{
    UIImageView *image_view = [[UIImageView alloc] initWithFrame:CGRectMake(MARGIN_LEFT*2, MARGIN_TOP, 30.f, 30.f)];
    [image_view setImage:[UIImage imageNamed:imageName]];
    
    return image_view;
}

- (UILabel *)createLabel:(NSString *)title
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(MARGIN_LEFT*6, MARGIN_TOP, currentDeviceWidth-MARGIN_LEFT*7, 30.f)];
    [label setText:title];
    
    return label;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TSUserModel *model = [rowsArray objectAtIndex:indexPath.row];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UIImageView *view = [self findImageViewInCell:cell];
    if ([view.image isEqual:[UIImage imageNamed:@"cell_not_selected"]]) {
        [selectedUserModel addObject:model];
        [view setImage:[UIImage imageNamed:@"cell_selected"]];
        [rowsSelectedArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:YES]];
    }
    else{
        [selectedUserModel removeObject:model];
        [view setImage:[UIImage imageNamed:@"cell_not_selected"]];
        [rowsSelectedArray replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:NO]];
    }
    
}

- (UIImageView *)findImageViewInCell:(UITableViewCell *)cell
{
    for (UIView *view in cell.contentView.subviews) {
        if ([view isKindOfClass:[UIImageView class]]) {
            return (UIImageView *)view;
        }
    }
    
    return nil;
}


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        if([self.title isEqualToString:@"接收人"]||[self.title isEqualToString:@"审核人"]){
            [self getAllUsers:textField.text];
        }else{
            
        }
        return NO;
    }
    return YES;
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self complete];
    }
    else if (buttonIndex == 1){
        [self selectAll];
    }
    else if (buttonIndex == 2){
        [self selectNone];
    }
}

-(void)selectNone
{
    [selectedUserModel removeAllObjects];
    [self.tableView reloadData];
}

-(void)selectAll
{
    for(TSUserModel *userModel in nowList){
        if(![selectedUserModel containsObject:userModel]){
            [selectedUserModel addObject:userModel];
        }
    }
    [self.tableView reloadData];
}
-(void)complete
{
    [[NSNotificationCenter defaultCenter] postNotificationName:TSNotification_OnMultipleSelectCompelete object:@{TSDictionaryKeyDefine_Name:[self findAllYesNames], TSDictionaryKeyDefine_Type:@(self.toolBarTextFieldType)?:@"",@"section":[NSString stringWithFormat:@"%d",section]}];
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
/* 设置textField属性 */
- (void)setUpFieldProperties:(UITextField *)field{
    field.backgroundColor =[UIColor whiteColor];
    field.tintColor = [UIColor grayColor];
    field.font = FONT(12);
    field.layer.cornerRadius = 5.f;
    field.layer.borderColor = [UIColor grayColor].CGColor;
    field.layer.borderWidth = .5f;
    field.delegate = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 5)];
    field.leftView = view;
    field.leftViewMode = UITextFieldViewModeAlways;
    field.returnKeyType = UIReturnKeyDone;
}

@end
